package com.smxy.daydayup.controller;

import com.smxy.daydayup.mapper.CourseMapper;
import com.smxy.daydayup.mapper.SignMapper;
import com.smxy.daydayup.pojo.Course;
import com.smxy.daydayup.pojo.SectionTree;
import com.smxy.daydayup.pojo.Teacher;
import com.smxy.daydayup.pojo.User;
import com.smxy.daydayup.pojo.dto.StudyCourseInfo;
import com.smxy.daydayup.service.CourseScoreService;
import com.smxy.daydayup.service.CourseService;
import com.smxy.daydayup.service.CourseTalkService;
import com.smxy.daydayup.service.SectionTreeService;
import com.smxy.daydayup.service.TeacherService;
import com.smxy.daydayup.service.feign.ZfRest;
import com.smxy.daydayup.util.IdUtil;
import com.smxy.daydayup.util.JwtUtils;
import com.smxy.daydayup.util.datetime.DateUtil;
import com.smxy.daydayup.util.result.ResultUtil;
import com.smxy.daydayup.util.result.ReturnResult;
import com.smxy.daydayup.util.result.StatusCode;
import com.smxy.daydayup.util.tree.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @team daydayup
 * @time 2021/12/11 17:51
 */

@Api(tags = "课程控制器")
@RestController
@RequestMapping("/course")
public class CourseController {

    // 自动装配上需要的业务层
    @Autowired
    CourseService courseService;
    @Autowired
    CourseScoreService courseScoreService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    SectionTreeService sectionTreeService;
    @Autowired
    CourseTalkService courseTalkService;
    @Autowired
    SignMapper signMapper;
    @Autowired
    CourseMapper courseMapper;

    @ApiOperation("显示所有已学课程的接口")
    @ApiImplicitParam(
            name = "userId",
            value = "用户id",
            required = true,
            dataTypeClass = String.class
    )
    @GetMapping("/show")    //通过用户id去查询该用户下面添加的课程（五张表联表查询（study_course,study_teacher,study_user,study_school,study_course_score））
    public ReturnResult userCourse(HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        return ResultUtil.returnSuccess(courseService.selectCourse(userInfoByToken.getUserId()), "课程信息");
    }

    @ApiOperation("添加课程的接口")
    @ApiImplicitParam(
            name = "userId",
            value = "用户id",
            required = true,
            dataTypeClass = String.class
    )
    @PostMapping("/addcourse")   //通过课程的邀请码往指定用户id去添加该课程
    public ReturnResult addCourse(    HttpServletRequest request,
                                      @RequestParam("courseCode") String courseCode) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        String mark = courseMapper.selectCode(courseCode);
        if(mark==null){
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"课程邀请码错误");
        }
        StudyCourseInfo studyCourseInfo = new StudyCourseInfo(userInfoByToken.getUserId(), courseCode, DateUtil.getNowDate(), DateUtil.getNowDate());
        courseScoreService.insertStudyCourse(studyCourseInfo);
        return ResultUtil.returnSuccess("添加的课程信息");
    }

    @ApiOperation("显示所有已教课程的接口")
    @ApiImplicitParam(
            name = "userId",
            value = "用户id",
            required = true,
            dataTypeClass = String.class
    )
    @GetMapping("/showprofessorCourse")  //通过用户id去查找哪门课的老师的用户id与之相等（两张表联表查询）
    public ReturnResult professorCourse(HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        return ResultUtil.returnSuccess(courseService.selectprofessorCourse(userInfoByToken.getUserId()), "课程信息");
    }

    @Resource
    ZfRest zfRest;
    @ApiOperation("新建课程的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "courseCover",
                    value = "课程封面",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "courseName",
                    value = "课程名",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "courseIntroduce",
                    value = "课程简介",
                    required = true,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "gmtStart",
                    value = "开课时间",
                    required = false,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "gmtEnd",
                    value = "结课时间",
                    required = false,
                    dataTypeClass = String.class
            ),
            @ApiImplicitParam(
                    name = "userId",
                    value = "用户id",
                    required = true,
                    dataTypeClass = String.class
            )
    })
    @PostMapping("/newcourse")   //传入课程的基本信息然后执行插入语句（基本的增添语句）
    public ReturnResult newCourse(@RequestParam("courseCover") String courseCover,
                                  @RequestParam("courseName") String courseName,
                                  @RequestParam("courseIntroduce") String courseIntroduce,
                                  @RequestParam(value = "gmtStart",required = false) String gmtStart,
                                  @RequestParam(value = "gmtEnd",required = false) String gmtEnd,
                                  HttpServletRequest request) {
        User userInfoByToken = JwtUtils.getUserInfoByToken(request);
        if (userInfoByToken == null) {
            return ResultUtil.returnFail(StatusCode.SERVER_EXCEPTION,"未登录");
        }
        //LocalDateTime localDateTime1 = DateUtil.formatTime(gmtStart); //转换成指定的时间格式（yyyy-mm-dd hh:mm:ss）
        //LocalDateTime localDateTime2 = DateUtil.formatTime(gmtEnd);//转换成指定的时间格式（yyyy-mm-dd hh:mm:ss）
        String code = IdUtil.getBaseID(); //随机生成一个唯一的课程邀请码（10位数）
        Course course = new Course(null, courseName, courseCover, courseIntroduce, DateUtil.getNowDate(), DateUtil.getNowDate(), null, code, 0, 0, DateUtil.getNowDate(), DateUtil.getNowDate());
        //实例化那个对象
        courseService.insert(course);//插入课程
        Integer courseId = courseService.selectCourseIdByCode(code);//获取课程id
        teacherService.insertSelective(new Teacher(null, courseId, userInfoByToken.getUserId(), 1, DateUtil.getNowDate(), DateUtil.getNowDate()));
        //插入老师与课程信息（让它们建立联系）  这样是为了知道这个课程是哪个老师教的
        List<SectionTree> initTree = TreeUtils.constructInitTreeByResolve();//实例化章节树
        sectionTreeService.updateTree(initTree,courseId);//保存章节树

        ZfRest.QuestionBank qBank = new ZfRest.QuestionBank();
        qBank.setBankId(courseId);
        qBank.setBankName(course.getCourseName());
        zfRest.addQBank(qBank, JwtUtils.createZFToken(userInfoByToken, courseId, true));

        return ResultUtil.returnSuccess();
    }


}
